const express = require("express");
const route = express.Router();
const {addUser, getAll, findUser} = require('../services/userServices')
const {validateAccount, addCount} = require('../services/accountServices')
const {formatResponseData, responseDataOmit} = require("../utils/response");
const {handleObjPropertyTo} = require("../utils/object");
const {pick, omit} = require("lodash");
const {sign} = require("../utils/jwt");


route.get('/all', async (req, res) => {
    const data = await getAll();
    res.send(formatResponseData(200, data, '操作成功'))
})

route.post('/submit', async (req, res) => {
    const userInfo = req.body;
    const accountInfo = pick(userInfo, ['username', 'password'])
    await addCount(accountInfo);
    const data = await addUser(omit(userInfo, ['password']));
    res.send(formatResponseData(200, data, '用户添加成功'))
})

route.get('/find', async (req, res) => {
    const userInfo = req.query;
    handleObjPropertyTo(userInfo, 'age', Number)
    const data = await findUser(userInfo);
    res.send(formatResponseData(200, data, '用户查找成功'))
})

route.get('/whoami', async (req, res) => {
    if (req.user) {
        res.send(formatResponseData(200, req.user.originalData ? responseDataOmit(req.user.originalData) : responseDataOmit(req.user), '用户查找成功'))
    } else {
        res.send(formatResponseData(500, null, '用户信息查找失败'))
    }
})


route.get('/login', async (req, res) => {
    const isRemember = req.query.isRemember;
    const accountInfo = pick(req.query, ['username', 'password']);
    const validateResult = await validateAccount(accountInfo);
    const userInfo = await findUser({username: accountInfo.username});

    const token = sign({type: 'account', id: userInfo[0]._id}, isRemember ? '7d' : '1d');
    if (!validateResult) {
        res.send(formatResponseData(500, null, '账号名或密码错误'))
    } else {
        res.send(formatResponseData(200, token, '登录成功'))
    }
})


module.exports = route;